<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :http-request="uploadImage"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <div slot="tip" class="el-upload__tip">支持扩展名：jpg、png、文件不得大于100kb</div>
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'UploadImage',
  props: {
    value: {
      type: String,
      default: null
    }
  },
  methods: {

    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    uploadImage (data) {
      console.log(data)
      const cos = new COS({
        // 秘钥id
        SecretId: 'AKID42FNJ4eDey9gDbovseVGsMhs4CTl1ELI',
        // 秘钥
        SecretKey: 'ukOtIUSanqrkVGrH7qPuMhzHRRL5f8Xn'
      })
      cos.putObject({
        Bucket: 'zzh-1318639262',
        Region: 'ap-nanjing',
        Key: data.file.name,
        StorageClass: 'STANDARD',
        Body: data.file
      }, (err, data) => {
        if (err) {
          this.$message.error(err.Message)
        }
        if (data.statusCode === 200 && data.Location) {
          // 拿到了腾讯云返回的地址
          // 通过input自定义事件将地址传出去
          this.$emit('input', 'http://' + data.Location)
        } else {
          // 上传失败提示消息
          this.$message.error(err.Message)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
  ::v-deep.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 84px;
    height: 84px;
    line-height: 84px;
    text-align: center;
  }
  .avatar {
    width: 84px;
    height: 84px;
    display: block;
  }
</style>
